#!/bin/bash

# Tiny QA - 快速构建脚本
# 利用Docker缓存，只重新构建应用代码部分

set -e

echo "🚀 Tiny QA - 快速构建"
echo "========================================"

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker未运行，请先启动Docker"
    exit 1
fi

# 构建参数
IMAGE_NAME="tiny-qa"
TAG="latest"
BUILD_CONTEXT="."

echo "📦 构建参数:"
echo "  镜像名称: $IMAGE_NAME"
echo "  标签: $TAG"
echo "  构建上下文: $BUILD_CONTEXT"
echo ""

# 使用BuildKit加速构建
export DOCKER_BUILDKIT=1

echo "🔨 开始构建..."
echo "⏱️  预计时间: 2-5分钟 (利用缓存)"
echo ""

# 构建镜像
docker build \
    --target app \
    --tag "${IMAGE_NAME}:${TAG}" \
    --file Dockerfile \
    --build-arg BUILDKIT_INLINE_CACHE=1 \
    --progress=plain \
    "${BUILD_CONTEXT}"

# 检查构建结果
if [ $? -eq 0 ]; then
    echo ""
    echo "✅ 构建成功！"
    echo ""
    echo "📋 镜像信息:"
    docker images "${IMAGE_NAME}:${TAG}" --format "table {{.Repository}}\t{{.Tag}}\t{{.ID}}\t{{.CreatedAt}}\t{{.Size}}"
    echo ""
    echo "🚀 运行命令:"
    echo "  docker run -d -p 5002:5002 -v \"/path/to/documents:/app/data/documents\" --name tiny-qa ${IMAGE_NAME}:${TAG}"
    echo ""
    echo "🔍 查看日志:"
    echo "  docker logs -f tiny-qa"
    echo ""
    echo "🌐 访问地址:"
    echo "  http://localhost:5002"
    echo ""
    echo "💡 提示:"
    echo "  - 首次运行需要下载AI模型"
    echo "  - 使用 ./scripts/check-models.sh 检查模型状态"
    echo "  - 使用 ./scripts/docker-start-with-docs.sh 快速启动"
else
    echo ""
    echo "❌ 构建失败！"
    echo "请检查错误信息并重试"
    exit 1
fi 